/** Part of Zombie Navigator
	Copyright © 2016  Zombie Navigator Developers
	
	@file
	@module
	@license AGPL-3.0+
	
*/ 'use strict';


/* Used modules */
const _pSandbox = require('../platform/sandbox');
const _pModuleLoader = require('../platform/module-loader');
const _pLogger = require('../platform/logger');
const _pPolicies = require('../platform/policies');
const _pScriptSession = require('../platform/script-session');
const _pUri = require('../platform/uri');


/* Private properties */

/**
	Whitelist of allowed pseudo-module IDs
	@private
*/
const _moduleIDs = [
	'zombie/zombie'
	, 'zombie/webbrowser'
	, 'zombie/async'
];


/* Internal APIs */

/**
	Run a Zombie script in a sandboxed environment
	@public
*/
const runScript = function (scriptURI) {
	const pSandbox = _pSandbox;
	const pModuleLoader = _pModuleLoader;
	const pLogger = _pLogger;
	const pPolicies = _pPolicies;
	const pUri = _pUri;
	const pScriptSession = _pScriptSession;
	
	const versionedURI = pUri.resolve(scriptURI + '', '?' + (new Date).getTime());
	
	const policies = pPolicies.createManager(versionedURI);
	
	// Show GUI notification
	pLogger.notify('Running script: ' + versionedURI);
	
	const session = pScriptSession.createSession(versionedURI, policies);
	return new Promise((resolve, reject) => {
		session.onSessionStart(() => {
			// Pseudo-modules available to Zombie scripts
			const modules = pModuleLoader.loadModules(_moduleIDs);
			const sandbox = pSandbox.runInSandbox(versionedURI, modules, session);
			session.onQuit(() => {
				sandbox.terminate();
				session.closeAll();
				console.log('terminated??');
			});
		});
	});
};


/* Exports */
exports.runScript = runScript;


// vim: ts=4 noet ai

